import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_play_android/common/common.dart';
import 'package:flutter_play_android/data/api/apis_service.dart';
import 'package:flutter_play_android/data/model/wx_chapter_model.dart';
import 'package:flutter_play_android/ui/wechat/wechat_article_screen.dart';
import 'package:flutter_play_android/utils/toast_util.dart';

import '../base/base_widget.dart';

class WeChatScreen extends BaseWidget {
  const WeChatScreen({Key? key}) : super(key: key);

  @override
  BaseWidgetState<BaseWidget> attachState() => _WeChatScreenState();
}

class _WeChatScreenState extends BaseWidgetState with TickerProviderStateMixin {
  final List<WXChaptersBean> _chaptersList = [];

  TabController? _tabController;

  @override
  void initState() {
    setAppBarShow(true);
    super.initState();
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    showLoading().then((value) {
      getWXChaptersList();
    });
    super.didChangeDependencies();
  }

  @override
  AppBar? attachAppBar() {
    _tabController = TabController(length: _chaptersList.length, vsync: this);
    return AppBar(
      title: TabBar(
          labelColor: Colors.white,
          unselectedLabelColor: Colors.white54,
          labelStyle: const TextStyle(fontSize: 15),
          unselectedLabelStyle: const TextStyle(fontSize: 12),
          isScrollable: true,
          controller: _tabController,
          tabs: _chaptersList.map((e) => Tab(text: e.name)).toList()),
    );
  }

  @override
  Widget attachContentWidget(BuildContext context) {
    return Container(
        width: double.infinity,
        height: double.infinity,
        alignment: AlignmentDirectional.topCenter,
        child: InkWell(
          onTap: () {},
          child: Expanded(
              child: TabBarView(
            controller: _tabController,
            children: _chaptersList
                .map((item) => WeChatArticleScreen(item.id ?? 0))
                .toList(),
          )),
        ));
  }

  @override
  void onClickErrorWidget() {}

  Future getWXChaptersList() async {
    apiService.getWXChaptersList((WXChaptersModel wxChaptersModel) {
      if (wxChaptersModel.errorCode == Constants.STATUS_SUCCESS) {
        if ((wxChaptersModel.data?.length ?? -1) > 0) {
          showContent();
          setState(() {
            _chaptersList.clear();
            _chaptersList.addAll(wxChaptersModel.data ?? []);
          });
        } else {
          showEmpty();
        }
      } else {
        showError();
        ToastUtil.show(msg: wxChaptersModel.errorMsg ?? '');
      }
    }, (DioError error) {
      showError();
    });
  }
}
